/////////////////////////////////////////////////////////////////////////////
//
// CodeLib.cpp
//
//
/////////////////////////////////////////////////////////////////////////////

#include "StdAfx.h"
#include "CodeLib.h"


/////////////////////////////////////////////////////////////////////////////
// CCodeLib

/////////////////////////////////////////////////////////////////////////////
// CCodeLib constructor and destructor

CCodeLib::CCodeLib()
{
}

CCodeLib::~CCodeLib()
{
}

/////////////////////////////////////////////////////////////////////////////
// Implementation

std::wstring CCodeLib::UTF8ToUnicode( const char* pchIn )
{
    size_t wcsLen = ::MultiByteToWideChar(CP_UTF8, NULL, pchIn, -1, NULL, 0);
 
    wchar_t* wszString = new wchar_t[wcsLen + 1];
 
    memset(wszString, 0, sizeof(wchar_t)*(wcsLen + 1));
 
    ::MultiByteToWideChar(CP_UTF8, NULL, pchIn, -1, wszString, wcsLen);
 
	std::wstring wstr = wszString;
 
    delete []wszString;
    return wstr;
}

void CCodeLib::UnicodeToGB2312( char* pchOut, unsigned short uData )
{
	::WideCharToMultiByte( CP_ACP, NULL, (LPCWSTR)&uData, 1, pchOut, sizeof( WCHAR ), NULL, NULL );
}

void CCodeLib::GB2312ToUnicode( WCHAR* pwchOut, const char* pchIn )
{
	::MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, pchIn, 2, pwchOut, 1 );
}

std::string CCodeLib::UnicodeToUTF8( const WCHAR* pwchIn )
{
	//unicode to utf8
	int nLen = WideCharToMultiByte(CP_UTF8, 0, pwchIn, -1, NULL, 0, NULL, NULL);
	if (nLen<= 0) 
		return std::string("");

	char* strBuf = new char[nLen];
	WideCharToMultiByte(CP_UTF8, 0, pwchIn, -1, strBuf, nLen, NULL, NULL);
	strBuf[nLen -1] = 0;
	std::string strConverted(strBuf);

	delete []strBuf;

	return strConverted;
}

std::wstring CCodeLib::GB2312ToUnicode( const char* pchIn )
{
    size_t wcsLen = ::MultiByteToWideChar(CP_ACP, NULL, pchIn, -1, NULL, 0);
 
    wchar_t* wszString = new wchar_t[wcsLen + 1];
 
    memset(wszString, 0, sizeof(wchar_t)*(wcsLen + 1));
 
    ::MultiByteToWideChar(CP_ACP, NULL, pchIn, -1, wszString, wcsLen);
 
	std::wstring wstr = wszString;
 
    delete []wszString;
    return wstr;
}

std::string CCodeLib::UnicodeToGB2312( const WCHAR* pwchIn )
{
	int nLen = WideCharToMultiByte(CP_ACP, 0, pwchIn, -1, NULL, 0, NULL, NULL);
	if (nLen<= 0) 
		return std::string("");

	char* strBuf = new char[nLen];
	WideCharToMultiByte(CP_ACP, 0, pwchIn, -1, strBuf, nLen, NULL, NULL);
	strBuf[nLen -1] = 0;
	std::string strConverted(strBuf);

	delete []strBuf;

	return strConverted;
}

std::string CCodeLib::GB2312ToUTF8( const char* pchIn )
{
	//Unicode
	std::wstring str = GB2312ToUnicode(pchIn);
	//UTF-8
	std::string out = UnicodeToUTF8(str.c_str());
	return out;
}

std::string CCodeLib::UTF8ToGB2312( const char* pchIn )
{
	//Unicode
	std::wstring str = UTF8ToUnicode(pchIn);
	//UTF-8
	std::string out = UnicodeToGB2312(str.c_str());
	return out;
}